package com.jianzh5.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jianzh5.common.DataPage;
import com.jianzh5.dao.BaseDaoI;
import com.jianzh5.entity.TAdmin;
import com.jianzh5.entity.TResource;
import com.jianzh5.entity.TRole;
import com.jianzh5.common.DataTables;
import com.jianzh5.pojo.PAdmin;
import com.jianzh5.pojo.PResources;
import com.jianzh5.service.UserServiceI;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service("userService")
public class UserServiceImpl implements UserServiceI{
	
	@Autowired
	private BaseDaoI<TAdmin> adminDao;
	@Autowired
	private BaseDaoI<TRole> roleDao;

	public TAdmin getByAccount(String username) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = "from TAdmin t where t.username = :username";
		params.put("username", username);
		TAdmin t = adminDao.get(hql, params);
		return t;
	}
	
	/**
	 * 用户登录获取当前用户所有信息
	 */
	public PAdmin getPadmin(int id) {
		String hql = "from TAdmin t left join fetch t.TRoles role left join fetch role.TResources resource where t.id = :id";
		Map<String, Object> params = Maps.newHashMap();
		params.put("id", id);
		TAdmin t = adminDao.get(hql, params);
		List<PResources> plist = Lists.newArrayList();
		PAdmin p = new PAdmin();
		if(t != null){
			Set<TRole> roles = t.getTRoles();
			if(roles != null && !roles.isEmpty()){
				String roleids = "";
				for(TRole role : roles){
					roleids += role.getId()+",";
					Set<TResource> resources = role.getTResources();
					if(resources != null && !resources.isEmpty()){
						for(TResource res : resources){
							PResources menu = new PResources();
							BeanUtils.copyProperties(res, menu);
							if(res.getTResource() != null){
								menu.setPid(res.getTResource().getId());
							}
							plist.add(menu);
						}
					}
				}
				roleids = roleids.substring(0,roleids.lastIndexOf(","));
			}
		}
		BeanUtils.copyProperties(t, p);
		p.setMenuList(plist);
		return p;
	}

	/**
	 * 用户管理员列表
	 */
	public DataTables dataTables(String order, String sort, DataPage datapage) {
		String hql = "from TAdmin t";
		String totalHql = "select count(*) from TAdmin t";
		hql += " order by t."+sort+" "+ order;
		List<TAdmin> tlist = adminDao.find(hql);
		List<PAdmin> plist = Lists.newArrayList();
		for(TAdmin t : tlist){
			PAdmin p = new PAdmin();
			BeanUtils.copyProperties(t, p);
			Set<TRole> roles = t.getTRoles();
			if(roles != null && !roles.isEmpty()){
				String rolenames = "";
				for(TRole role : roles){
					rolenames += role.getRolename()+",";
				}
				rolenames = rolenames.substring(0,rolenames.lastIndexOf(","));
				p.setRoleNames(rolenames);
			}
			plist.add(p);
		}
		long records = adminDao.count(totalHql);
		
		DataTables dt = new DataTables();
		dt.setDraw(datapage.getDraw());
		dt.setRecordsTotal(records);
		dt.setRecordsFiltered(records);
		dt.setData(plist);
		return dt;
	}

	/**
	 * 查询要编辑用户的信息
	 * 到权限，不用查询资源
	 */
	public PAdmin getPadminWithRole(int id) {
		Map<String, Object> params = Maps.newHashMap();
		PAdmin padmin = new PAdmin();
		params.put("id", id);
		String hql = "from TAdmin t left join fetch t.TRoles r where t.id = :id ";
		TAdmin t = adminDao.get(hql,params);
		BeanUtils.copyProperties(t, padmin);
		Set<TRole> roles = t.getTRoles();
		if(roles != null && !roles.isEmpty()){
			String roleids = "";
			String rolenames = "";
			for(TRole role : roles){
				roleids += role.getId()+",";
				rolenames += rolenames+",";
			}
			roleids = roleids.substring(0,roleids.lastIndexOf(","));
			rolenames = rolenames.substring(0,rolenames.lastIndexOf(","));
			padmin.setRoleIds(roleids);
			padmin.setRoleNames(rolenames);
		}
		BeanUtils.copyProperties(t, padmin);
		return padmin;
	}

	/**
	 * 编辑后台管理用户...
	 */
	public void editUser(PAdmin admin) {
		System.out.println("用户信息:"+admin.toString());
		TAdmin t = adminDao.get(TAdmin.class, admin.getId());
		BeanUtils.copyProperties(admin, t, new String[]{"password"});
		//如果密码不为空则设置新密码，否则与原密码保持一致
		if(admin.getPassword() != null && !admin.getPassword().equals("")){
			t.setPassword(new Md5Hash(admin.getPassword(),null,1).toString());
		}
		Set<TRole> roleSet = Sets.newHashSet();
		if(admin.getRoleIds() != null && !admin.getRoleIds().equals("")){
			for(String roleId : admin.getRoleIds().split(",")){
				TRole role = roleDao.get(TRole.class, Integer.parseInt(roleId));
				roleSet.add(role);
			}
		}
		t.setTRoles(roleSet);
	}

	public void addUser(PAdmin admin) {
		TAdmin t = new TAdmin();
		BeanUtils.copyProperties(admin, t, new String[]{"password"});
		//第一种MD5简单设置
		String password = new Md5Hash(admin.getPassword(),null,1).toString();
		t.setPassword(password);
		//第二种复杂设置
	//	DefaultHashService hashService = new DefaultHashService();
	//	HashRequest request = new HashRequest.Builder()  
    //   .setAlgorithmName("MD5")
    //    .setSource(new SimpleByteSource(admin.getPassword()))
    //    .setIterations(1).build();  
	//	String password = hashService.computeHash(request).toHex();
	//	System.out.println("加密密码为:"+password);
		
		Set<TRole> roleSet = Sets.newHashSet();
		if(StringUtils.isNotBlank(admin.getRoleIds())){
			for(String str : admin.getRoleIds().split(",")){
				TRole role = roleDao.get(TRole.class, Integer.parseInt(str));
				roleSet.add(role);
			}
		}
		t.setTRoles(roleSet);
		adminDao.save(t);
	}

	public void delUser(int userId) {
		TAdmin t = adminDao.get(TAdmin.class, userId);
		adminDao.delete(t);
		
	}
	
}	
